#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2017/12/7 0007 21:09
# @Author  : Arliki
# @email   : hkdnxycz@outlook.com
# @File    : check.py
import time


class Test(object):
    # 外部调用仅仅可以从slots锁包含的属性调用 同时 类内不可重复使用
    __slots__ = ('name', 'score', 'stu_nu', 'class_room', 'birthday')
    stu_nua = '99999'

    def set_score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self.score = value

    def get_score(self):
        return self.score

    def get_stu_nua(self):
        return self.stu_nua

    def get_stu_nu(self):
        return self.stu_nu

    # property 将类里面的方法设置成属性进行返回（需对应**.setter【设置值】，不设置则改属性为只读）
    @property
    def birth(self):
        return self.birthday

    @birth.setter
    def birth(self, val):
        self.birthday = int(val)

    @property
    def age(self):
        return int(time.strftime('%Y', time.localtime())) - self.birthday


a = Test()
a.set_score(80)
a.stu_nu = '91'
a.birth = '1996'
print(a.get_score())
print(a.stu_nua)
print(a.get_stu_nu())
print(a.birth)
print(a.age)
o = object


class Chain(object):
    def __init__(self, path=''):
        self._path = path

    def __getattr__(self, path):
        return Chain('%s/%s' % (self._path, path))

    def __str__(self):
        return self._path

    __repr__ = __str__


print(Chain().list.asd)
# type创建类
asd = type('typetest', (object,), {"test1": '321123', "test2": lambda x: x + 4})
print(asd().test1)


# ↓↓↓↓↓↓↓↓↓↓metaclass new用法
def add(self, index):
    self.pop(index)


class mhMetaClass(type):
    def __new__(cls, name, bases, attrs):
        print("创建一个%s%s%s%s" % (cls, name, bases, attrs))
        attrs['add'] = add
        return type.__new__(cls, name, bases, attrs)


class mhlist(list, metaclass=mhMetaClass):
    pass


l = mhlist()
l.append(1)
l.append(2)
l.append(3)
l.append(4)
l.add(2)
print(l)


# ↑↑↑↑↑↑↑↑↑↑↑↑ super()用法
class C(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age


class D(C):
    def __init__(self, name, age, sax):
        super().__init__(name, age)
        self.sax = sax

    def __str__(self):
        return "%s%s%s" % (self.name, self.age, self.sax)


d = D('qawkm', 123, 321)
print(d)


# ↓↓↓↓↓↓↓↓orm实例数据库--test
#  wtf 没弄懂
class field(object):
    def __init__(self, name, type):
        self.name = name
        self.type = type

    def __str__(self):
        return "<%s:%s>" % (self.name, self.type)


class intfield(field):
    def __init__(self, name, type='int(10)'):
        super().__init__(name, type)


class strfield(field):
    def __init__(self, name, type='varchar(200)'):
        super().__init__(name, type)


class schoolmetaclass(type):
    def __new__(cls, name, bases, attrs):
        mapping = dict()
        print('mapping:%s' % (mapping))
        for k, v in attrs.items():
            if isinstance(v, field):
                print('类的属性和方法--%s:%s' % (k, v))
                mapping[k] = v
        # 移除类属性
        for k in mapping.keys():
            attrs.pop(k)
        attrs['__mapping__'] = mapping
        attrs['__table__'] = name
        # print(attrs)
        return type.__new__(cls, name, bases, attrs)


class baseschool(dict, metaclass=schoolmetaclass):
    def __init__(self, **kw):
        # print(kw)
        super().__init__(**kw)

    def __getattr__(self, key):
        return self[key]

    def __setattr__(self, key, value):
        self[key] = value

    def save(self):
        column = []
        parms = []
        args = []
        for k, v in self.__mapping__.items():
            column.append(v.name)
            parms.append('?')
            args.append(getattr(self, k, None))
        sql = 'insert into %s (%s) VALUES %s' % (self.__table__, ','.join(column), ','.join(parms))
        print("sql:%s" % (sql))
        print(str(args))


class school(baseschool):
    name = strfield('name')
    id = intfield('id')
    email = strfield('email')


stu = school(name='www', id='90909', email='asdwqe@123')
stu.save()
print(stu.name)
#↑↑↑↑↑↑↑↑yes
